package xin.petstore.framework.file.hash;

import java.io.File;
import java.io.IOException;

public class FileHashUtils {
    public static String getMD5HashValue(String fileName, int length) {
        try {
            String result = getMD5HashValue(fileName);
            if (length > 32) {
                return result;
            }
            return result.substring(0, length);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getMD5HashValue(String fileName) throws IOException {
        IHashCalc hash = HashCalc.getFileInstance(fileName, new String[]{"MD5"});
        setInterceptor(hash);
        String[] results = hash.getHexStringHash();
        return results[0];
    }

    public static String getMD5HashValue(File file) throws IOException {
        IHashCalc hash = HashCalc.getFileInstance(file, new String[]{"MD5"});
        setInterceptor(hash);
        String[] results = hash.getHexStringHash();
        return results[0];
    }

    private static void setInterceptor(IHashCalc hash) {
        hash.addHashProgressInterceptor(new HashProgressInterceptor() {
            public void bytesRead(HashBuffer buffer, IHashCalc calc) {
                long finished = calc.getReadCount();
                long total = ((File) calc.getSource()).length();
                System.out.println(String.format("read %d bytes,%.2f%%", new Object[]{
                        Integer.valueOf(buffer.getLength()), Double.valueOf(finished * 100.0D / total)}));
            }
        });
    }
}
